"""
用友云Token签名生成工具

用于生成符合用友云开放平台规范的Token请求签名
"""
import hmac
import hashlib
import base64
import time
from urllib.parse import quote


def calculate_signature(app_key: str, app_secret: str, timestamp: int = None) -> dict:
    """
    计算用友云Token请求签名

    参数:
        app_key: 应用的appKey
        app_secret: 应用的appSecret
        timestamp: 毫秒级时间戳（不传则自动生成）

    返回:
        包含完整请求参数的字典
    """
    # 如果没有传入时间戳，生成当前时间的毫秒级时间戳
    if timestamp is None:
        timestamp = int(time.time() * 1000)

    # 1. 按参数名称排序并拼接：appKeyXXXtimestampYYY
    param_string = f"appKey{app_key}timestamp{timestamp}"

    # 2. 使用HmacSHA256加密
    hmac_obj = hmac.new(
        app_secret.encode('utf-8'),
        param_string.encode('utf-8'),
        hashlib.sha256
    )
    signature_bytes = hmac_obj.digest()

    # 3. Base64编码
    base64_signature = base64.b64encode(signature_bytes).decode('utf-8')

    # 4. URL编码
    url_encoded_signature = quote(base64_signature, safe='')

    return {
        'appKey': app_key,
        'timestamp': timestamp,
        'signature': url_encoded_signature,
        'signature_base64': base64_signature  # 用于调试
    }


def generate_token_url(base_url: str, app_key: str, app_secret: str) -> str:
    """
    生成完整的Token请求URL

    参数:
        base_url: 基础URL（如：http://127.0.0.1:3003）
        app_key: 应用的appKey
        app_secret: 应用的appSecret

    返回:
        完整的Token请求URL
    """
    params = calculate_signature(app_key, app_secret)

    url = (f"{base_url}/iuap-api-auth/open-auth/selfAppAuth/base/v1/getAccessToken"
           f"?appKey={params['appKey']}"
           f"&timestamp={params['timestamp']}"
           f"&signature={params['signature']}")

    return url


if __name__ == '__main__':
    # 示例：使用测试应用的凭证
    print("=" * 70)
    print("用友云Token签名生成工具")
    print("=" * 70)

    # 测试应用1
    app_key_1 = 'test_app_key'
    app_secret_1 = 'test_app_secret'

    print("\n【测试应用1】")
    print(f"App Key: {app_key_1}")
    print(f"App Secret: {app_secret_1}")

    result_1 = calculate_signature(app_key_1, app_secret_1)
    print(f"\n请求参数:")
    print(f"  appKey: {result_1['appKey']}")
    print(f"  timestamp: {result_1['timestamp']}")
    print(f"  signature: {result_1['signature']}")
    print(f"\n签名计算过程:")
    print(f"  1. 拼接字符串: appKey{app_key_1}timestamp{result_1['timestamp']}")
    print(f"  2. HmacSHA256加密（密钥：{app_secret_1}）")
    print(f"  3. Base64编码: {result_1['signature_base64']}")
    print(f"  4. URL编码: {result_1['signature']}")

    # 生成完整URL
    base_url = 'http://127.0.0.1:3003'
    full_url = generate_token_url(base_url, app_key_1, app_secret_1)
    print(f"\n完整请求URL:")
    print(f"  {full_url}")

    # 测试应用2（MES集成应用示例）
    print("\n" + "=" * 70)
    app_key_2 = '41832a3d2df94989b500da6a22268747'
    app_secret_2 = 'your_secret_here'

    print("\n【MES集成应用】")
    print(f"App Key: {app_key_2}")
    print(f"App Secret: {app_secret_2}")

    result_2 = calculate_signature(app_key_2, app_secret_2)
    print(f"\n请求参数:")
    print(f"  appKey: {result_2['appKey']}")
    print(f"  timestamp: {result_2['timestamp']}")
    print(f"  signature: {result_2['signature']}")

    full_url_2 = generate_token_url(base_url, app_key_2, app_secret_2)
    print(f"\n完整请求URL:")
    print(f"  {full_url_2}")

    print("\n" + "=" * 70)
    print("\n使用curl测试命令:")
    print(f'curl -X GET "{full_url_2}"')
    print("\n或者使用Python requests:")
    print(f"""
import requests

url = "{full_url_2}"
response = requests.get(url)
print(response.json())
""")
    print("=" * 70)
